package com.qingcheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.goods.SpuService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Elsticsearch {

    @Autowired
    private SpuService spuService;

    @Autowired
    private SkuService skuService;


    public static void main(String[] args) throws Exception {

        SkuServiceImpl skuService = new SkuServiceImpl();
        //连接rest接口
        HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(http);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        boolean flag=true;
        int i = 90810/1000+1;
        int j = 1;
        while (flag){
            if (j==i){
                flag=false;
            }
            PageResult<Sku> page = skuService.findPage(j++, 1000);
            List<Sku> rows = page.getRows();
            BulkRequest bulkRequest = new BulkRequest();
            for (Sku sku : rows) {
                IndexRequest indexRequest = new IndexRequest("sku", "doc", sku.getId());

                Map skuMap = new HashMap();
                Map spec = new HashMap();
                skuMap.put("name",sku.getName());
                skuMap.put("brandName",sku.getBrandName());
                skuMap.put("categoryName",sku.getCategoryName());
                skuMap.put("price",sku.getPrice());
                skuMap.put("create",sku.getCreateTime());
                skuMap.put("saleNum",sku.getSaleNum());
                skuMap.put("commentNum",sku.getCommentNum());
                //{'颜色': '红色', '版本': '8GB+128GB'}
                Map<String,Object> map=(Map) JSON.parseObject(sku.getSpec(),Map.class);
                for (String key : map.keySet()) {
                    spec.put(key,map.get(key));
                }
                skuMap.put("spec",spec);

                indexRequest.source(skuMap);

                bulkRequest.add(indexRequest);

            }
            //获取响应结果
            BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            int status = responses.status().getStatus();
            System.out.println(status);

        }

        restHighLevelClient.close();


    }



    public void saveAllToES() throws IOException {


    }

    public  void save() throws IOException {
        //连接rest接口
        HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(http);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);


        BulkRequest bulkRequest = new BulkRequest();
        IndexRequest indexRequest = new IndexRequest("sku", "doc", "3");
        Map skuMap = new HashMap();
        skuMap.put("name","华为p30pro");
        skuMap.put("brandName","华为");
        skuMap.put("categoryName","手机");
        skuMap.put("price","4000");
        skuMap.put("create","2019-05-01");
        skuMap.put("saleNum","101021");
        skuMap.put("commentNum","10012321");
        Map spec = new HashMap();
        spec.put("网络制式","移动4G");
        spec.put("屏幕尺寸","5");
        skuMap.put("spec",spec);
        indexRequest.source(skuMap);

        bulkRequest.add(indexRequest);
        //获取响应结果
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        int status = responses.status().getStatus();
        System.out.println(status);
        restHighLevelClient.close();
    }

    //匹配查询接口
    public void matchFind() throws IOException {
        //连接rest接口
        HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(http);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);

        //封装查询请求 (查询sku库中的doc表)
        SearchRequest searchRequest = new SearchRequest("sku");
        searchRequest.types("doc");

        //查询条件(name="手机")
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "手机");

        searchSourceBuilder.query(matchQueryBuilder);
        searchRequest.source(searchSourceBuilder);

        //获取查询结果
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = searchResponse.getHits();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
        }

        restHighLevelClient.close();
    }
    //bool与词条查询
    public void boolFind() throws Exception {
        //1.连接rest接口
        HttpHost http=new HttpHost("127.0.0.1",9200,"http");
        RestClientBuilder builder= RestClient.builder(http);//rest构建器
        RestHighLevelClient restHighLevelClient=new RestHighLevelClient(builder);//高级客户端对象 （连接）


        //2.封装查询请求
        SearchRequest searchRequest=new SearchRequest("sku");
        searchRequest.types("doc"); //设置查询的类型

        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();//布尔查询构建器

        MatchQueryBuilder matchQueryBuilder= QueryBuilders.matchQuery("name","手机");
        boolQueryBuilder.must(matchQueryBuilder);

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "小米");
        boolQueryBuilder.must(termQueryBuilder);

        searchSourceBuilder.query(boolQueryBuilder);

        searchRequest.source(searchSourceBuilder);


        //3.获取查询结果

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = searchResponse.getHits();
        long totalHits = searchHits.getTotalHits();
        System.out.println("记录数："+totalHits);
        SearchHit[] hits = searchHits.getHits();
        for(SearchHit hit:hits){
            String source = hit.getSourceAsString();
            System.out.println(source);
        }
        restHighLevelClient.close();
    }

    //bool查询
    public void boolTwoFind() throws IOException {

        //1.连接rest接口
        HttpHost http=new HttpHost("127.0.0.1",9200,"http");
        RestClientBuilder builder= RestClient.builder(http);//rest构建器
        RestHighLevelClient restHighLevelClient=new RestHighLevelClient(builder);//高级客户端对象 （连接）

        //2.封装查询请求
        SearchRequest searchRequest=new SearchRequest("sku");
        searchRequest.types("doc"); //设置查询的类型
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();//布尔查询构建器

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brandName", "小米");
        boolQueryBuilder.filter(termQueryBuilder);

        searchSourceBuilder.query(boolQueryBuilder);

        searchRequest.source(searchSourceBuilder);


        //3.获取查询结果

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = searchResponse.getHits();
        long totalHits = searchHits.getTotalHits();
        System.out.println("记录数："+totalHits);
        SearchHit[] hits = searchHits.getHits();
        for(SearchHit hit:hits){
            String source = hit.getSourceAsString();
            System.out.println(source);
        }
        restHighLevelClient.close();

    }

    //过滤查询
    public void filtterFind() throws Exception {

        //1.连接rest接口
        HttpHost http=new HttpHost("127.0.0.1",9200,"http");
        RestClientBuilder builder= RestClient.builder(http);//rest构建器
        RestHighLevelClient restHighLevelClient=new RestHighLevelClient(builder);//高级客户端对象 （连接）

        //2.封装查询请求
        SearchRequest searchRequest=new SearchRequest("sku");
        searchRequest.types("doc"); //设置查询的类型
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("sku_category").field("categoryName");
        searchSourceBuilder.aggregation(termsAggregationBuilder);
        searchSourceBuilder.size(0);

        searchRequest.source(searchSourceBuilder);

        //3.获取查询结果
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        Aggregations aggregations = searchResponse.getAggregations();
        Map<String, Aggregation> aggregationMap = aggregations.getAsMap();

        Terms terms = (Terms) aggregationMap.get("sku_category");

        List<? extends Terms.Bucket> buckets =  terms.getBuckets();
        for( Terms.Bucket bucket:buckets ){
            System.out.println( bucket.getKeyAsString()+":"+bucket.getDocCount() );
        }
        restHighLevelClient.close();

    }




}
